package top.tenebrous.yzl.chain;


import top.tenebrous.yzl.context.JesticContext;
import top.tenebrous.yzl.context.JesticTask;
import top.tenebrous.yzl.context.Response;

/**
 * @Description:
 * @Project: jestic-spring-boot
 * @Package: com.zy.tenebrous.jestic.chain
 * @Author: zhangya
 * @CreateTime: 2023-06-28  17:56
 * @Version: 1.0.0
 */
public abstract class AbstractJesticChainHandler<T extends JesticTask, C extends Response> {

    protected AbstractJesticChainHandler<T, C> nextHandler;

    public void nextHandler(AbstractJesticChainHandler<T, C> nextHandler) {
        this.nextHandler = nextHandler;
    }

    public abstract void handler(JesticContext<? extends JesticTask, ? extends Response> context);

    public abstract int order(String taskType);

    public abstract int getOrder();

    public abstract AbstractJesticChainHandler<T, C> setOrder(int order);

    public static class Builder<T extends JesticTask, C extends Response> {

        private AbstractJesticChainHandler<T, C> head;

        private AbstractJesticChainHandler<T, C> tail;

        public Builder<T, C> addHandler(AbstractJesticChainHandler<T, C> handler) {
            // 如果为空，则插入头节点
            if (this.head == null) {
                this.head = this.tail = handler;
                return this;
            }

            this.tail.nextHandler(handler);
            this.tail = handler;
            return this;
        }

        public AbstractJesticChainHandler<T, C> build() {
            return this.head;
        }

    }
}
